package com.dms.modules.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dms.common.exception.BusinessException;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.mapper.MerchantMapper;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.entity.ProductComment;
import com.dms.modules.product.mapper.ProductCommentMapper;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.modules.merchant.dto.MerchantCommentBatchReplyDTO;
import com.dms.modules.merchant.dto.MerchantCommentTemplateDTO;
import com.dms.modules.merchant.entity.MerchantCommentTemplate;
import com.dms.modules.merchant.mapper.MerchantCommentTemplateMapper;
import com.dms.modules.merchant.service.MerchantCommentService;
import com.dms.modules.merchant.vo.MerchantCommentTrendVO;
import com.dms.modules.product.vo.CommentStatisticsVO;
import com.dms.modules.product.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家评论服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MerchantCommentServiceImpl implements MerchantCommentService {

    private final ProductCommentMapper productCommentMapper;
    private final MerchantCommentTemplateMapper commentTemplateMapper;
    private final ProductService productService;
    private final MerchantMapper merchantMapper;

    @Override
    public IPage<CommentVO> getProductComments(Long productId, Page<CommentVO> page) {
        return productCommentMapper.selectProductComments(productId, page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean replyComment(Long commentId, String reply, Long userId) {
        // 1. 获取评论信息
        ProductComment comment = productCommentMapper.selectById(commentId);
        if (comment == null) {
            throw new BusinessException("评论不存在");
        }

        // 2. 获取商品信息
        Product product = productService.getById(comment.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }

        // 3. 根据userId获取商家信息
        LambdaQueryWrapper<Merchant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Merchant::getUserId, userId);
        Merchant merchant = merchantMapper.selectOne(wrapper);
        if (merchant == null) {
            throw new BusinessException("商家信息不存在");
        }

        // 4. 验证商品是否属于当前商家
        if (!product.getMerchantId().equals(merchant.getId())) {
            log.warn("商家用户[{}]尝试回复非自己商品[{}]的评论[{}]", userId, product.getId(), commentId);
            throw new BusinessException("无权回复该评论");
        }

        // 5. 更新评论回复
        comment.setReply(reply);
        comment.setReplyTime(LocalDateTime.now());
        return productCommentMapper.updateById(comment) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchReplyComments(MerchantCommentBatchReplyDTO dto) {
        boolean success = true;
        for (Long commentId : dto.getCommentIds()) {
            success = success && replyComment(commentId, dto.getReply(), dto.getMerchantId());
        }
        return success;
    }

    @Override
    public CommentStatisticsVO getCommentStatistics(Long productId) {
        return productCommentMapper.selectCommentStatistics(productId);
    }

    @Override
    public List<MerchantCommentTrendVO> getCommentTrend(Long productId, Integer days) {
        return productCommentMapper.selectCommentTrend(productId, days);
    }

    @Override
    public void exportComments(Long productId, HttpServletResponse response) {
        // TODO: 实现评论导出功能
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createReplyTemplate(MerchantCommentTemplateDTO dto, Long userId) {
        // 1. 获取商家信息
        LambdaQueryWrapper<Merchant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Merchant::getUserId, userId);
        Merchant merchant = merchantMapper.selectOne(wrapper);
        if (merchant == null) {
            throw new BusinessException("商家信息不存在");
        }

        // 2. 创建模板
        MerchantCommentTemplate template = new MerchantCommentTemplate();
        BeanUtils.copyProperties(dto, template);
        template.setMerchantId(merchant.getId());
        template.setCreateTime(LocalDateTime.now());
        template.setUpdateTime(LocalDateTime.now());
        commentTemplateMapper.insert(template);
        return template.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateReplyTemplate(Long id, MerchantCommentTemplateDTO dto, Long userId) {
        // 1. 获取商家信息
        LambdaQueryWrapper<Merchant> merchantWrapper = new LambdaQueryWrapper<>();
        merchantWrapper.eq(Merchant::getUserId, userId);
        Merchant merchant = merchantMapper.selectOne(merchantWrapper);
        if (merchant == null) {
            throw new BusinessException("商家信息不存在");
        }

        // 2. 获取并验证模板是否存在
        MerchantCommentTemplate template = commentTemplateMapper.selectById(id);
        if (template == null) {
            throw new BusinessException("模板不存在");
        }

        // 3. 验证模板是否属于当前商家
        if (!template.getMerchantId().equals(merchant.getId())) {
            throw new BusinessException("无权修改此模板");
        }

        // 4. 更新模板信息
        template.setName(dto.getName());
        template.setContent(dto.getContent());
        template.setType(dto.getType());
        template.setUpdateTime(LocalDateTime.now());
        
        return commentTemplateMapper.updateById(template) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteReplyTemplate(Long id) {
        return commentTemplateMapper.deleteById(id) > 0;
    }

    @Override
    public List<MerchantCommentTemplateDTO> getReplyTemplates() {
        return commentTemplateMapper.selectList(null)
                .stream()
                .map(template -> {
                    MerchantCommentTemplateDTO dto = new MerchantCommentTemplateDTO();
                    BeanUtils.copyProperties(template, dto);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    @Override
    public IPage<CommentVO> getMerchantComments(Long merchantId, Page<CommentVO> page, Integer rating, 
            Boolean hasImage, String sortField, String sortOrder) {
        log.info("获取商家[{}]所有商品评论列表", merchantId);
        
        // 1. 获取商家所有商品ID
        List<Long> productIds = productService.lambdaQuery()
            .eq(Product::getMerchantId, merchantId)
            .list()
            .stream()
            .map(Product::getId)
            .collect(Collectors.toList());
            
        if (productIds.isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize());
        }

        // 2. 构建查询条件
        return productCommentMapper.selectMerchantComments(page, productIds, rating, hasImage, sortField, sortOrder);
    }
} 